package dao;



import exception.NotMatchException;
import model.Renovate;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RenovateTableDao {

    private RenovateTableDao() {
    }

    public static List<Renovate> getRenovates() throws SQLException {
        List<Renovate> list = new ArrayList<>();

        String sql = "select student.s_no,student.s_name,score.c_name,score.renovate_score " +
                "from student,score " +
                "where student.s_no=score.s_no and makeup_score<60";

        PreparedStatement stmt = Dao.getConnection().prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            String sno = rs.getString(rs.findColumn("s_no"));
            String sname = rs.getString(rs.findColumn("s_name"));
            String cname = rs.getString(rs.findColumn("c_name"));
            int makeupScore = rs.getInt(rs.findColumn("renovate_score"));

            Renovate renovate = new Renovate();
            renovate.setSno(sno);
            renovate.setSname(sname);
            renovate.setCname(cname);
            renovate.setRevonateScore(makeupScore);

            list.add(renovate);
        }

        return list;
    }

    public static void saveRenovates(List<Renovate> renovates) throws Exception {
        int rowIndex = 0;
        try {
            while (rowIndex < renovates.size()) {
                Renovate renovate = renovates.get(rowIndex);
                saveRenovate(renovate);
                rowIndex++;
            }
        } catch (NotMatchException e) {
            throw new NotMatchException("第 " + rowIndex + " 行，" + e.getMessage());
        }

    }

    public static void saveRenovate(Renovate renovate) throws Exception {
        String sno = renovate.getSno();
        String sname = renovate.getSname();
        String cname = renovate.getCname();
        int renovateScore = renovate.getRevonateScore();

        Dao.checkMatch(sno, sname, cname);

        String sql = "Update score " +
                "set renovate_score=? where s_no=? and c_name=?";
        PreparedStatement stmt = Dao.getConnection().prepareStatement(sql);

        stmt.setInt(1, renovateScore);
        stmt.setString(2, sno);
        stmt.setString(3, cname);

        stmt.execute();
    }
}
